import api from './api/index'
import setter from './config'
import {
    msg,
    hide
} from '../utils/dialog.js';
import store from '@/store/index.js';
/**
 * 描述数据平台返回的状态
 */
const resposeStatus = {
    //无动作
    None: 0,
    //成功
    Sucess: 1,
    //警告
    Warning: 2,
    //失败
    Fail: 3,
    //未授权
    NoAuth: 4,
    //异常
    Error: 5,
    //跳转
    Redirect: 6
}
/**
 * 组织URL
 * @param {String} module  
 * @param {String} operation 
 */
const makeUrl = (module, operation) => {
    let result = {
        status: false,
        method: 'GET',
        url: '',
        auth: true,
    }
    const funName = api[module] || api.auth;
    if (!funName) {
        console.error(`api中不存在{module}`);
        return result;
    }
    const action = funName[operation] || api.auth.login;
    if (!funName) {
        console.error(`api模块{module}中不存在{operation}`);
        return result;
    }

    if (typeof action === 'string') {
        result = {
            status: true,
            method: 'GET',
            url: setter.remote + action,
            auth: true,
        }
        return result;
    } else {
        if (!action.url) {
            console.error(`api模块{module}中{operation}不存在url`);
            return result;
        }
        let method = 'GET';
        if ((action.method || 'post').toLowerCase() === 'post') {
            method = 'POST';
        }
        return {
            status: true,
            method: method,
            url: setter.remote + action.url,//获取最终url=service.config+service.api.action.url
            auth: !!action.auth,
        };
    }
}

/**
 * 正确返回数据体，非正常返回带code的数据
 * @param {String} module  
 * @param {String} operation  
 * @param {Object} data 请求参数
 * @param {Object} ext 附加参数
 * @param {Number} ext.cache 数据缓存时间，秒
 */
export const request = (module, operation, data = {}, ext = {}) => {
    return new Promise((resolve, reject) => {
        try {
            let action = makeUrl(module, operation);
            if (action.status === false) {
                reject({
                    code: resposeStatus.Error,
                    msg: '数据出错'
                });
            }
            if (ext.cache > 0) {
                const cacheResult = cache.get(operation + '-' + operation);
                if (cacheResult !== false && cacheResult.status !== 0) {
                    resolve(cacheResult);
                    return;
                }
            }

            // 参数未定义处理
            let params = Object.assign({}, data);
            let headers = {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                'Accept': 'application/json, text/plain, */*'
            };
            // 需要token校验，请求参数添加token
            if (action.auth === true) {
                const token = store.getters.getToken;
                if (!store.getters.hasLogin || !token) {
                    hide();
                    //授权过期，需要重新登录了
                    // console.log('action','token:'+token,store.getters.hasLogin,action,module,operation)
                    uni.showModal({
                        title: '提示',
                        content: '登录后才可以操作',
                        confirmText: '去登录',
                        showCancel: false,
                        success: function(res) {
                            uni.reLaunch({
                                url: '/pages/auth/login'
                            })
                        }
                    });
                    return;
                }
                headers['Access-Token'] = token;
            }
			
            uni.request({
                url: action.url,
                method: action.method,
                data: params,
                header: headers,
				
                success: res => {
                    let resdata = res.data;
					
                    switch (resdata.code) {
                        //无动作
                        case resposeStatus.None:
                            msg(resdata.msg);
                            reject({
                                code: resposeStatus.None,
                                msg: '无信息提示'
                            })
                            break;
                        case resposeStatus.Sucess:
                        case resposeStatus.Error:
                        case resposeStatus.Redirect:
                        case resposeStatus.Fail:
                            resolve(resdata);
                            break;
                        case resposeStatus.NoAuth:
                            //授权过期，需要重新登录了
                            uni.showModal({
                                title: '提示',
                                content: '登录后才可以操作',
                                confirmText: '去登录',
                                showCancel: false,
                                success: function(res) {
                                    uni.reLaunch({
                                        url: '/pages/auth/login'
                                    })
                                }
                            });
                            //清除登录信息
                            store.commit('logout');
                            reject({
                                code: resposeStatus.NoAuth,
                                msg: '登录信息已过期，请重新登录'
                            })
                            break;
                        default:
                            reject({
                                code: resposeStatus.Error,
                                msg: '数据请求失败'
                            })
                            break;
                    }
                },
                fail: res => {
                    //错误提示框
                    resolve({
                        code: resposeStatus.Error,
                        msg: '数据请求失败'
                    })
                },
                complete() {
                    if (process.env.NODE_ENV === 'development') {
                        // console.log('Reponse GET:', action.url, arguments)
                    }
                }
            })
        } catch (e) {
            reject({
                code: resposeStatus.Error,
                msg: e
            })
        }
    })
}

/**
 * 上传文件，file支持file对象或file数组
 * @param {file} file  
 * @param {Object} data 请求参数
 */
export const upload = (module, operation, file, data = {}, ext = {}) => {
	
    module = module || 'file';
    operation = operation || 'uploadImg';
    return new Promise((resolve, reject) => {
        // 参数未定义处理
        let formdata = Object.assign({}, data);
        let headers = {
            'Accept': 'application/json;charset=UTF-8'
        };
        let action = makeUrl(module, operation);
		
        if (action.status === false) {
            reject({
                code: resposeStatus.Error,
                msg: '数据出错'
            });
        }
        // 需要token校验，请求参数添加token
        if (action.auth === true) {
            const token = store.getters.getToken;
            if (!store.getters.hasLogin || !token) {
                //授权过期，需要重新登录了
                uni.showModal({
                    title: '提示',
                    content: '登录后才可以操作',
                    confirmText: '去登录',
                    showCancel: false,
                    success: function(res) {
                        uni.reLaunch({
                            url: '/pages/auth/login'
                        })
                    }
                });
                reject({
                    code: resposeStatus.Error,
                    msg: '请重新登录'
                });
                return;
            }
            headers['Access-Token'] = token;
        }
        if (process.env.NODE_ENV === 'development') {
            // console.log('Request GET:', action.url, formdata);
        }
        //如果是数组说明是多文件上传
        let fileary = [];
        if (file instanceof Array) {
            fileary = [...file];
        } else {
            fileary.push(file);
        }
        let uploads = [];
        fileary.forEach((item, i) => {
            uploads[i] = new Promise((resolve, reject) => {
                //网络请求
                uni.uploadFile({
                    url: action.url,
                    filePath: item,
                    name: 'AvatarFile',
                    header: headers,
                    formData: data,
                    success: res => {
						
                        let resdata = JSON.parse(res.data);
                        switch (resdata.code) {
                            //无动作
                            case resposeStatus.None:
                            case resposeStatus.Error:
                            case resposeStatus.Redirect:
                            case resposeStatus.Fail:
                                reject({
                                    code: resposeStatus.Error,
                                    index: i,
                                    msg: resdata.msg
                                })
                                break;
                            case resposeStatus.Sucess:
                                resolve({
                                    code: resdata.code,
                                    index: i,
                                    data: resdata.data
                                })
                                break;
                            case resposeStatus.NoAuth:
                                store.commit('logout');
                                reject({
                                    code: resposeStatus.NoAuth,
                                    msg: '登录信息已过期，请重新登录'
                                })
                                break;
                            default:
                                reject({
                                    code: resposeStatus.Error,
                                    msg: '数据请求失败'
                                })
                                break;
                        }
                    },
                    fail: res => {
                        console.error(res)
                        reject({
                            code: resposeStatus.Error,
                            index: i,
                            msg: '数据请求失败'
                        })
                    },
                    complete() {
                        if (process.env.NODE_ENV === 'development') {
                            // console.log('Reponse GET:', action.url, arguments)
                        }
                    }
                })
            })
        })
        Promise.all(uploads).then(res => {
            //图片上传完成
            var remoteFilePath = [];
            res.forEach((item, index) => {
                if (item.code === resposeStatus.Sucess) {
                    remoteFilePath.push(item.data)
                }
            })
            resolve({
                code: resposeStatus.Sucess,
                msg: 'sucess',
                data: remoteFilePath
            })
        }).catch(err => {
            reject({
                code: resposeStatus.Fail,
                msg: err.msg,
                data: null
            })
        })
    })
}
